package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService service;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = service.findByusername(username);
        if (sysUser == null){
            return null;
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (Role role : sysUser.getRoles()) {
            for (Permission permission : role.getPermissions()) {
                String keyword = permission.getKeyword();
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(keyword);
                authorityList.add(grantedAuthority);
            }
        }
        User user = new User(sysUser.getUsername(),sysUser.getPassword(),authorityList);
        return user;
    }
}
